<template>
  <view class="booking-container">
    <!-- 状态栏占位 -->
    <view class="status-bar"></view>
    
    <!-- 导航栏 -->
    <view class="header">
      <view class="nav-content">
        <view class="back-btn" @tap="goBack">
          <text class="back-icon">←</text>
        </view>
        <text class="title">{{ categoryName || '疫苗预约' }}</text>
        <view class="placeholder"></view>
      </view>
    </view>

    <!-- 疫苗列表 -->
    <view class="vaccine-list" v-if="!selectedVaccine">
      <view v-if="vaccineList.length === 0" class="empty-tip">
        <text>暂无疫苗数据</text>
      </view>
      
      <view 
        class="vaccine-item" 
        v-for="vaccine in vaccineList" 
        :key="vaccine.id"
        @tap="selectVaccine(vaccine)"
      >
        <view class="vaccine-info">
          <view class="vaccine-header">
            <text class="vaccine-name">{{ vaccine.name }}</text>
            <text class="vaccine-tag" v-if="vaccine.isHot === 1">热门</text>
          </view>
          <text class="vaccine-desc">{{ vaccine.description }}</text>
          <text class="vaccine-prevention" v-if="vaccine.preventionDescription">
            {{ vaccine.preventionDescription }}
          </text>
          <view class="vaccine-detail">
            <text class="manufacturer" v-if="vaccine.manufacturer">
              生产厂家：{{ vaccine.manufacturer }}
            </text>
            <text class="storage" v-if="vaccine.storageCondition">
              储存条件：{{ vaccine.storageCondition }}
            </text>
          </view>
          <view class="vaccine-bottom">
            <view class="price-box">
              <text class="price-label">价格：</text>
              <text class="price">¥{{ vaccine.price }}</text>
              <text class="original-price" v-if="vaccine.originalPrice">¥{{ vaccine.originalPrice }}</text>
            </view>
            <button class="book-btn" @tap.stop="selectVaccine(vaccine)">立即预约</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 预约表单 -->
    <view class="booking-form" v-if="selectedVaccine">
      <view class="form-title">{{ selectedVaccine.name }} - 预约信息</view>
      
      <view class="form-item">
        <text class="item-label">选择医院</text>
        <picker @change="onHospitalChange" :value="hospitalIndex" :range="hospitals" range-key="name">
          <view class="picker-content">
            <text v-if="appointmentData.hospitalId">{{ hospitals[hospitalIndex].name }}</text>
            <text v-else class="placeholder-text">请选择医院</text>
            <text class="picker-arrow">▼</text>
          </view>
        </picker>
      </view>
      
      <!-- 医院详情信息 -->
      <view class="hospital-detail" v-if="selectedHospital">
        <view class="hospital-image" v-if="selectedHospital.imgurl">
          <image :src="selectedHospital.imgurl" mode="aspectFill"></image>
        </view>
        <view class="detail-item">
          <text class="detail-label">地址：</text>
          <text class="detail-value">{{ selectedHospital.fullAddress }}</text>
        </view>
      </view>
      
      <view class="form-item">
        <text class="item-label">预约日期</text>
        <picker mode="date" :value="appointmentData.appointmentDate" :start="startDate" :end="endDate" @change="onDateChange">
          <view class="picker-content">
            <text v-if="appointmentData.appointmentDate">{{ appointmentData.appointmentDate }}</text>
            <text v-else class="placeholder-text">请选择日期</text>
            <text class="picker-arrow">▼</text>
          </view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="item-label">预约时间</text>
        <view class="time-slots">
          <view 
            v-for="(slot, index) in timeSlots" 
            :key="index"
            class="time-slot-item"
            :class="{ 
              active: appointmentData.appointmentTime === slot.value,
              disabled: slot.disabled 
            }"
            @tap="selectTimeSlot(slot.value)"
          >
            {{ slot.label }}
          </view>
        </view>
      </view>
      
      <view class="form-item notes">
        <text class="item-label">预约须知</text>
        <view class="notes-content">
          <text>1. 预约成功后请按时前往医院接种。</text>
          <text>2. 如需取消预约，请提前24小时操作。</text>
          <text>3. 接种前请保持良好的身体状态，避免疲劳、饥饿。</text>
          <text>4. 接种后需留观30分钟，如有不适请立即告知医护人员。</text>
        </view>
      </view>
      
      <view class="form-actions">
        <button class="cancel-btn" @tap="cancelBooking">取消</button>
        <button class="submit-btn" @tap="submitBooking" :disabled="!isFormValid">提交预约</button>
      </view>
    </view>
  </view>
</template>

<script>
import { getVaccinesByCategoryId, createVaccinationAppointment} from '@/api/vaccination'
import { getHospitalList, getHospitalById, getHospitalNameById } from '@/api/hospital'

export default {
  data() {
    return {
      categoryId: '',
      categoryName: '',
      vaccineList: [],
      statusBarHeight: 0,
      selectedVaccine: null,
      hospitals: [],
      hospitalIndex: 0,
      timeSlots: [
        { label: '08:00-09:00', value: '08:00:00', disabled: false },
        { label: '09:00-10:00', value: '09:00:00', disabled: false },
        { label: '10:00-11:00', value: '10:00:00', disabled: false },
        { label: '11:00-12:00', value: '11:00:00', disabled: false },
        { label: '14:00-15:00', value: '14:00:00', disabled: false },
        { label: '15:00-16:00', value: '15:00:00', disabled: false },
        { label: '16:00-17:00', value: '16:00:00', disabled: false }
      ],
      appointmentData: {
        vaccineId: '',
        hospitalId: '',
        appointmentDate: '',
        appointmentTime: '',
        userId: '',
        status: 0
      },
      startDate: this.formatDate(new Date()),
      endDate: this.formatDate(new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)), // 30天后
      selectedHospital: null, // 当前选择的医院详细信息
      hospitalName: '' // 添加医院名称字段
    }
  },

  computed: {
    isFormValid() {
      return this.appointmentData.vaccineId && 
             this.appointmentData.hospitalId && 
             this.appointmentData.appointmentDate && 
             this.appointmentData.appointmentTime
    }
  },

  onLoad(options) {
    this.categoryId = options.categoryId
    this.categoryName = options.categoryName
    this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight
    
    // 如果直接有疫苗ID，则直接进入预约页面
    if (options.id) {
      // TODO: 获取疫苗详情
    }
    
    // 获取上一页传递的数据
    const pages = getCurrentPages()
    const prevPage = pages[pages.length - 2]
    if (prevPage && prevPage.$vm.categoryVaccines) {
      this.vaccineList = prevPage.$vm.categoryVaccines
    }
    
    // 默认选择当天日期
    this.appointmentData.appointmentDate = this.formatDate(new Date())
    
    // 初始化时就更新时间槽状态
    this.updateTimeSlotStatus()
    
    // 获取医院列表
    this.fetchHospitalList()
  },

  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    async fetchHospitalList() {
      try {
        const response = await getHospitalList()
        console.log('医院列表响应:', response)
        
        if (response.code === 200 && response.data) {
          // 处理特殊的嵌套数据结构
          this.hospitals = response.data.map(item => {
            // 将appHospital和appAddress中的数据合并处理
            return {
              id: item.appHospital.id,
              name: item.appHospital.name,
              imgurl: item.appHospital.imgurl,
              addressId: item.appHospital.addressId,
              // 地址信息
              province: item.appAddress.province,
              city: item.appAddress.city,
              district: item.appAddress.district,
              detailedAddress: item.appAddress.detailedAddress,
              // 完整地址
              fullAddress: `${item.appAddress.province} ${item.appAddress.city} ${item.appAddress.district} ${item.appAddress.detailedAddress}`
            }
          })
          
          console.log('处理后的医院数据:', this.hospitals)
        } else {
          throw new Error(response.errorMessage || '获取医院列表失败')
        }
      } catch (error) {
        console.error('获取医院列表失败：', error)
        uni.showToast({
          title: '获取医院列表失败',
          icon: 'none'
        })
      }
    },

    async fetchHospitalById(hospitalId) {
      try {
        uni.showLoading({
          title: '加载中...'
        })
        
        const response = await getHospitalById(hospitalId)
        
        if (response.code === 200 && response.data) {
          this.selectedHospital = response.data
          // 可以更新页面上其他需要显示的医院信息
          // 比如地址、联系电话等
        } else {
          throw new Error(response.errorMessage || '获取医院详情失败')
        }
      } catch (error) {
        console.error('获取医院详情失败：', error)
        uni.showToast({
          title: '获取医院详情失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    selectVaccine(vaccine) {
      // 检查登录状态
      const userInfo = uni.getStorageSync('userInfo')
      if (!userInfo) {
        uni.showModal({
          title: '提示',
          content: '请先登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/login/login'
              })
            }
          }
        })
        return
      }

      this.selectedVaccine = vaccine
      this.appointmentData.vaccineId = vaccine.id
      this.appointmentData.userId = userInfo.id
      
      // 默认选择当天
      this.appointmentData.appointmentDate = this.formatDate(new Date())
      
      // 立即更新时间槽状态
      this.updateTimeSlotStatus()
    },

    onHospitalChange(e) {
      this.hospitalIndex = e.detail.value
      const hospital = this.hospitals[this.hospitalIndex]
      this.appointmentData.hospitalId = hospital.id
      
      // 显示医院详情
      this.selectedHospital = hospital
      
      // 不再需要单独获取医院名称，因为已经在列表中
      // this.fetchHospitalNameById(hospital.id)
    },

    onDateChange(e) {
      this.appointmentData.appointmentDate = e.detail.value
      
      // 清除之前选择的时间
      this.appointmentData.appointmentTime = ''
      
      // 更新时间槽的可选状态
      this.updateTimeSlotStatus()
    },
    
    // 更新更严格的时间槽检查逻辑
    updateTimeSlotStatus() {
      const selectedDate = new Date(this.appointmentData.appointmentDate)
      const today = new Date()
      
      // 清除所有禁用状态
      this.timeSlots.forEach(slot => {
        slot.disabled = false
      })
      
      // 如果选择的是今天，禁用已经过去的时间段
      if (selectedDate.toDateString() === today.toDateString()) {
        const currentHour = today.getHours()
        const currentMinute = today.getMinutes()
        
        this.timeSlots.forEach(slot => {
          // 从时间字符串中提取小时
          const slotHour = parseInt(slot.value.split(':')[0])
          
          // 如果当前时间已经超过时间槽，或接近时间槽（预留30分钟缓冲）
          if (slotHour < currentHour || (slotHour === currentHour && currentMinute > 30)) {
            slot.disabled = true
            
            // 如果当前选中的时间已经被禁用，清除选择
            if (this.appointmentData.appointmentTime === slot.value) {
              this.appointmentData.appointmentTime = ''
            }
          }
        })
      }
      
      console.log('更新后的时间槽状态:', this.timeSlots)
    },

    selectTimeSlot(time) {
      // 找到对应的时间槽
      const slot = this.timeSlots.find(s => s.value === time)
      
      // 如果时间槽禁用，则不允许选择
      if (slot && slot.disabled) {
        uni.showToast({
          title: '该时段已过，请选择其他时间',
          icon: 'none'
        })
        return
      }
      
      this.appointmentData.appointmentTime = time
    },

    cancelBooking() {
      this.selectedVaccine = null
      this.appointmentData = {
        vaccineId: '',
        hospitalId: '',
        appointmentDate: '',
        appointmentTime: '',
        userId: this.appointmentData.userId,
        status: 0
      }
    },

    async submitBooking() {
      if (!this.isFormValid) {
        uni.showToast({
          title: '请完善预约信息',
          icon: 'none'
        })
        return
      }

      try {
        uni.showLoading({
          title: '提交中...'
        })
        
        const response = await createVaccinationAppointment(this.appointmentData)
        
        if (response.code === 200) {
          uni.showToast({
            title: '预约成功',
            icon: 'success'
          })
          
          // 延迟一下，让用户看到成功提示后再返回首页
          setTimeout(() => {
            // 返回到疫苗接种页面
            uni.navigateBack({
              delta: 1 // 返回上一页
            })
          }, 1500)
        } else {
          throw new Error(response.errorMessage || '预约失败')
        }
      } catch (error) {
        console.error('预约失败：', error)
        uni.showToast({
          title: error.message || '预约失败，请稍后再试',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    }
  },
  
  // 添加监听页面显示的生命周期钩子
  onShow() {
    // 如果已选择日期，更新时间槽状态
    if (this.appointmentData.appointmentDate) {
      this.updateTimeSlotStatus()
    }
  }
}
</script>

<style lang="scss">
.booking-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  
  .header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background-color: #fff;
    
    .nav-content {
      margin-top: 44px;
      display: flex;
      align-items: center;
      padding: 20rpx 30rpx;
      height: 88rpx;
      
      .back-btn {
        width: 24rpx;
        height: 24rpx;
        display: flex;
        align-items: center;
        
        .back-icon {
          font-size: 24rpx;
          color: #333;
        }
      }
      
      .title {
        flex: 1;
        text-align: center;
        font-size: 32rpx;
        color: #333;
        font-weight: bold;
      }
      
      .placeholder {
        width: 24rpx;
      }
    }
  }
  
  .vaccine-list {
    margin-top: calc(44px + 88rpx);
    padding: 20rpx;
    
    .vaccine-item {
      background-color: #fff;
      border-radius: 12rpx;
      padding: 30rpx;
      margin-bottom: 20rpx;
      
      .vaccine-header {
        display: flex;
        align-items: center;
        margin-bottom: 16rpx;
        
        .vaccine-name {
          font-size: 32rpx;
          color: #333;
          font-weight: bold;
        }
        
        .vaccine-tag {
          margin-left: 16rpx;
          padding: 4rpx 12rpx;
          font-size: 22rpx;
          color: #ff5500;
          background-color: #fff7f5;
          border-radius: 4rpx;
        }
      }
      
      .vaccine-desc, .vaccine-prevention {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 16rpx;
        line-height: 1.5;
      }
      
      .vaccine-detail {
        margin-bottom: 20rpx;
        
        .manufacturer, .storage {
          display: block;
          font-size: 26rpx;
          color: #666;
          margin-bottom: 8rpx;
        }
      }
      
      .vaccine-bottom {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .price-box {
          .price-label {
            font-size: 26rpx;
            color: #666;
          }
          
          .price {
            font-size: 36rpx;
            color: #ff5500;
            font-weight: bold;
          }
          
          .original-price {
            font-size: 24rpx;
            color: #999;
            text-decoration: line-through;
            margin-left: 12rpx;
          }
        }
        
        .book-btn {
          width: 160rpx;
          height: 64rpx;
          line-height: 64rpx;
          background-color: #ff5500;
          color: #fff;
          font-size: 28rpx;
          border-radius: 32rpx;
          padding: 0;
        }
      }
    }
    
    .empty-tip {
      text-align: center;
      padding: 60rpx 0;
      color: #999;
      font-size: 28rpx;
    }
  }
  
  .booking-form {
    margin-top: calc(44px + 88rpx);
    padding: 30rpx;
    
    .form-title {
      font-size: 32rpx;
      font-weight: bold;
      margin-bottom: 30rpx;
      color: #333;
    }
    
    .form-item {
      margin-bottom: 30rpx;
      background-color: #fff;
      border-radius: 12rpx;
      padding: 20rpx;
      
      .item-label {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 20rpx;
        display: block;
      }
      
      .picker-content {
        height: 80rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 20rpx;
        background-color: #f8f8f8;
        border-radius: 8rpx;
        
        .placeholder-text {
          color: #999;
        }
        
        .picker-arrow {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .time-slots {
        display: flex;
        flex-wrap: wrap;
        
        .time-slot-item {
          width: calc(33.33% - 20rpx);
          height: 80rpx;
          line-height: 80rpx;
          text-align: center;
          background-color: #f8f8f8;
          margin: 10rpx;
          border-radius: 8rpx;
          font-size: 26rpx;
          color: #666;
          
          &.active {
            background-color: #ffe7e0;
            color: #ff5500;
            font-weight: bold;
          }
          
          &.disabled {
            background-color: #eee;
            color: #ccc;
            position: relative;
            
            &::after {
              content: '';
              position: absolute;
              top: 50%;
              left: 50%;
              width: 80%;
              height: 2rpx;
              background-color: #ccc;
              transform: translate(-50%, -50%) rotate(-10deg);
            }
          }
        }
      }
      
      &.notes {
        .notes-content {
          font-size: 26rpx;
          color: #666;
          line-height: 1.6;
          
          text {
            display: block;
            margin-bottom: 10rpx;
          }
        }
      }
    }
    
    .hospital-detail {
      margin-top: -20rpx;
      margin-bottom: 30rpx;
      background-color: #f8f8f8;
      border-radius: 12rpx;
      padding: 20rpx;
      
      .hospital-image {
        width: 100%;
        height: 200rpx;
        margin-bottom: 20rpx;
        border-radius: 8rpx;
        overflow: hidden;
        
        image {
          width: 100%;
          height: 100%;
        }
      }
      
      .detail-item {
        margin-bottom: 10rpx;
        font-size: 26rpx;
        color: #666;
        display: flex;
        
        .detail-label {
          min-width: 140rpx;
          color: #999;
        }
        
        .detail-value {
          flex: 1;
          
          &.description {
            margin-top: 10rpx;
            line-height: 1.6;
            color: #999;
          }
        }
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
    
    .form-actions {
      display: flex;
      justify-content: space-between;
      margin-top: 40rpx;
      
      .cancel-btn, .submit-btn {
        width: 320rpx;
        height: 88rpx;
        line-height: 88rpx;
        border-radius: 44rpx;
        font-size: 30rpx;
      }
      
      .cancel-btn {
        background-color: #f5f5f5;
        color: #666;
      }
      
      .submit-btn {
        background-color: #ff5500;
        color: #fff;
        
        &[disabled] {
          background-color: #ffa88c;
        }
      }
    }
  }
}
</style> 